#include "my_task.hpp"
#include "tlv.h"
#include "tlv_type.h"
#include <shadow.h>
#include <iostream>
#include <vector>

using std::cout;
using std::endl;

my_task::my_task(shared_ptr<rocket::tcp_link>link,rocket::packet data)
:_link(link)
,_data(data)
{

}
my_task::~my_task()
{
}

void my_task::something()
{
    //打印接收到的数据
    cout<<"receive data= ";
    _data.print();
    
    //判断数据报文类型
    
    if (_data.get_type() == rocket::LOGIN_USER) 
    {
        //是登录发送用户名报文
	    cout << "type=LOGIN_USER" << endl;
        //根据用户名获取密文盐值等相关内容
	    spwd *pna = getspnam(_data.get_data().c_str());

	    //从字符串中分离出盐值
	    if (pna != NULL) 
        {
		    int salt_length = 0;
		    for (int i = 0, j = 0; i < strlen(pna->sp_pwdp); ++i) 
            {
			    if (pna->sp_pwdp[i] == '$') 
                {
				    ++j;
				    if (j == 4) 
                    {
					    salt_length = i;
					    break;
				    }
			    }
		    }
            char salt[1024] = { 0 };
	        strncpy(salt, pna->sp_pwdp, salt_length);
            //将发来的用户名存储在链接对象中
            _link->set_user(_data.get_data());
	        rocket::tlv salt_tlv(rocket::LOGIN_SALT, strlen(salt),salt);
            //发送盐值给客户端
	        _link->add_send_task(salt_tlv);
	        cout << "send_salt_tlv : ";
	        salt_tlv.print();
	    }else
        {
		    cout << "user name is not exist" << endl;
            //发送用户名不正确的报文给客户端
	        _link->add_send_task(rocket::tlv(rocket::LOGIN_RESULT,
                strlen("user_name_wrong"),
                "user_name_wrong"));

        }

    } 
    else if (_data.get_type() == rocket::LOGIN_CIPHERTEXT) 
    {
        //是登录发送密文报文
	    cout << "type=LOGIN_CIPHERTEXT" << endl;
        //根据前一次存储的用户名来获取到对应的密文
        spwd *ciphertext = getspnam(_link->get_user().c_str());
	    //判断密文是否匹配,并向客户端发送密文匹配结果
	    if (strcmp(_data.get_data().c_str(), ciphertext->sp_pwdp) == 0) 
        {
		    cout << "password is correct" << endl;
		    rocket::tlv result_tlv(rocket::LOGIN_RESULT,
					   strlen("success"), "success");
            _link->add_send_task(result_tlv);
		    cout << "send_result_tlv : " ;
		    result_tlv.print();
	    } else 
        {
		    cout << "password is wrong" << endl;
		    rocket::tlv result_tlv(rocket::LOGIN_RESULT,
					   strlen("success"), "success");

            _link->add_send_task(result_tlv);
		    cout << "send_result_tlv : " ;
		    result_tlv.print();
	    }

    }


}



